<template>
    <div class="print_view">
        <div class="header">
            <span class="txt">打印方式：</span>
            <el-radio-group v-model="printType">
                <el-radio :label="1">本机打印</el-radio>
                <el-radio :label="2">云打印</el-radio>
            </el-radio-group>
        </div>
        <!-- 本地打印 -->
        <template v-if="printType===1">
            <div class="steps">
                <el-steps direction="vertical" :active="3" finish-status="finish">
                    <el-step>
                        <div slot="title" style="font-size: 14px;">
                            下载安装驱动程序
                            <a style="margin-left: 26px;cursor: pointer;font-size: 13px;color: red;" 
                                href="https://anhuiyaoying.com/CLodop_Setup_for_Win32NT.exe">下载驱动程序</a>
                        </div>
                    </el-step>
                    <el-step>
                        <div slot="title" style="font-size: 14px;">
                            连接打印机，配置打印参数
                            <a style="margin-left: 26px;cursor: pointer;font-size: 13px;color: red;" target="_blank"
                                href="https://anhuiyaoying.com/连接打印机&打印参数设置操作手册.pdf">查看操作手册</a>
                        </div>
                    </el-step>
                    <el-step>
                        <div slot="title" style="font-size: 14px;">
                            选择需要打印的单据，点击下方打印按钮
                            <!-- <a style="margin-left: 26px;cursor: pointer;font-size: 13px;color: red;" target="_blank"
                                href="https://anhuiyaoying.com/单据本机打印操作手册.pdf">查看操作手册</a> -->
                        </div>
                    </el-step>
                </el-steps>
            </div>
            <div class="print_btn">
                <template v-if="!isPostOrder">
                    <div class="btn" @click="print('preview')">{{showPreview?'生成预览文件...':'打印'}}</div>
                </template>
                <template v-else>
                    <el-dropdown trigger="click" placement="bottom" @command="dropClick">
                        <div class="btn">打印</div>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="sale" >打印销售单</el-dropdown-item>
                            <el-dropdown-item command="post" >打印送货单</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
             </div>
        </template>
        <!-- 云打印 -->
        <template v-if="printType===2">
            <div v-if="yunheList&&yunheList.length" class="list">
                <div class="yunhe">{{ yunheText }}</div>
                <div v-if="deviceList&&deviceList.length">
                    <div class="print_list" v-for="item in deviceList" :key="'print_'+item.id">
                        <div class="card">
                            <div class="top">
                                <img :src="item.printIcon" alt="" />
                                <span style="margin-left: 15px;">{{item.printType+' | '+item.printer_name}}</span>
                            </div>
                            <div class="bottom">
                                <div class="txt">{{'型号: '+item.printer_name}}</div>
                                <div class="txt" v-if="item.ip_addr">{{'IP: '+item.ip_addr}}</div>
                                <div class="txt mohe" v-if="item.markers">
                                    <span style="margin-bottom: 6px;">估计耗材余量</span>
                                    <el-progress :percentage="item.percent" :show-text="false" :color="item.markers.black.color"></el-progress>
                                    <div v-if="item.markers.color_list&&item.markers.color_list.length" class="colorful">
                                        <el-progress 
                                            style="margin-top: 5px;"
                                            v-for="(_item, _index) in item.markers.color_list"
                                            :key="'color_'+_index"
                                            :percentage="_item.percent" 
                                            :show-text="false" 
                                            :color="_item.color">
                                        </el-progress>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="circle" :class="{select: item.selected}">
                            <i v-if="item.selected" style="font-size: 26px;color: #0099ff" class="el-icon-success"></i>
                        </div>
                    </div>
                </div>
                <div v-else>
                    <el-result subTitle="暂无可用的打印机设备">
                        <template slot="icon">
                            <el-image style="width: 200px;height: 200px;" src="https://anhuiyaoying.com/icon/no_list.png"></el-image>
                        </template>
                    </el-result>
                </div>
            </div>
            <div v-else>
                <el-result subTitle="暂无绑定的云盒设备">
                    <template slot="icon">
                        <el-image style="width: 200px;height: 200px;" src="https://anhuiyaoying.com/icon/no_list.png"></el-image>
                    </template>
                    <template slot="extra">
                        <el-button class="btn_primary_color" @click="showBandDeviceAlert=true" size="medium">绑定云盒</el-button>
                    </template>
                </el-result>
            </div>
            <div class="btns" v-if="deviceList&&deviceList.length">
                <div class="btn" @click="print('preview')">{{showPreview?'加载中...':'打印预览'}}</div>
                <div class="btn" @click="print">{{showPrint?'打印中...':'打印'}}</div>
            </div>
        </template>
        

        <el-dialog title="绑定云盒" :visible.sync="showBandDeviceAlert" @close="showBandDeviceAlert=false"
            center append-to-body>
            <div class="add_form">
                <el-form ref="addForm" :model="bandForm" :rules="rules" label-width="auto">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="云盒型号" prop="device_type">
                                <el-select style="width: 200px;" v-model="bandForm.device_type" placeholder="请选择">
                                    <el-option v-for="item in deviceTypes" :key="'pay_'+item.value" 
                                        :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="云盒名称:">
                                <el-input style="width: 200px" v-model="bandForm.device_name" placeholder="请输入" maxlength="20" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备序列号:" prop="device_id">
                                <el-input style="width: 200px" v-model="bandForm.device_id" placeholder="请输入" maxlength="50" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备密码:" prop="device_key">
                                <el-input style="width: 200px" v-model="bandForm.device_key" placeholder="请输入" maxlength="50" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showBandDeviceAlert=false">取 消</el-button>
                <el-button type="primary" @click="bandDeviceCommit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getBandDevices, getPrintLists, bandDevice, urlToPdf, addPrintTasks } from '@/api/common';
    import { getPrintSettings } from '@/api/unicloudApi';
    import { getToken } from '@/utils/auth';  

    export default {
		data() {
			return {
                showPreview: false,
                showPrint: false,
                showBandDeviceAlert: false,
				corp: '',
				yunheList: [],
				yunheText: '',
				deviceList: [],
                printType: 1,
				params: {},
                bandForm: {
                    device_id: '',
					device_key: '',
					device_type: 'LK100W',
					device_name: ''
                },
                rules:{
                    device_type: [
                        { required: true, message: "请选择云盒型号", trigger: "change" },
                    ],
                    device_id: [
                        { required: true, message: "请输入设备序列号", trigger: "blur" },
                    ],
                    device_key: [
                        { required: true, message: "请输入设备密码", trigger: "blur" },
                    ]
                },
                deviceTypes: [
					{label: 'LK100W', value: 'LK100W'},
					{label: 'LK200W', value: 'LK200W'},
					{label: 'LK300W', value: 'LK300W'},
                ]
            }
        },
        watch: {
            printObj: {
                handler(newVal) {
                    // 当 selectCustomers 变化时执行的操作
                    console.log('父组件 已更新', newVal.pk_id);
                    this.params = newVal
                },
                immediate: true,  //强制首次触发
                deep: true // 深度监听数组变化
            }
        },
        props: {
            printObj: {
                type: Object
            },
            isPostOrder: {
                type: Boolean,
                default: false
            }
        },
        mounted() {
            this.corp = this.$store.state.corpId
            this.getDeviceList()
			this.getPrintFields()
        },
        methods: {
            dropClick(c) {
                console.log(c);
                if (c == 'sale'){
                    this.print('preview')
                }else {
                    this.print('preview', true)
                }
            },
            // 获取云盒列表
			getDeviceList() {
				let corp = this.corp
				let that = this
				getBandDevices({ corp }).then(res => {
					that.yunheList = res.data
					if (res.data.length) {
						let type = res.data[0].device_name || res.data[0].device_type
						that.yunheText = '【云盒】'+ type
						that.getPrintList()
					}
				})
			},
			// 获取云盒下连接的打印机列表
			getPrintList() {
                let param = {
                    corp: this.corp,
                    printer_type: '1'
                }
				getPrintLists(param).then(res => {
					this.deviceList = res.data.row.filter((item, index) => {
						item.selected = false
						if (index == 0){
							item.selected = true
						}
						if (String(item.port) == '631'){  //网络打印机
							item.printIcon = 'https://anhuiyaoying.com/icon/net.png'
							item.printType = '网络'
						}else {
							item.printIcon = 'https://anhuiyaoying.com/icon/print.png'
							item.printType = 'USB'+item.port
						}
						if (item.markers) {
							item.percent = (item.markers.black.level / item.markers.black.high_level)*100
							
							if (item.markers.color_list && item.markers.color_list.length){
								item.markers.color_list.forEach(_item => {
									_item.percent = (_item.level / _item.high_level)*100
								})
							}
						}
						return item
					})
                    this.showBandDeviceAlert = false
				})
			},
			// 获取打印设置字段
			getPrintFields() {
				let that = this
                getPrintSettings({
                    corp_id: this.corp,
                    type: this.params.type
                }).then(res => {
                    if (res.data.length) {
                        that.params.selectedSize = res.data[0].pageSize
                    }else{
                        that.params.selectedSize = '1'
                    }
                })
			},
            print(type, is_post) {
                let print_dict = {}
                switch (this.params.selectedSize) {
					case '1':  //A4
						print_dict = {}
						break;
					case '2':  //A4二等分
						print_dict = {
							page_height: 13.9,
							page_width: 21.0,
							orientation: "portrait",
							header_template: "",
							footer_template: ""
						}
						break;
					case '3':  //A4三等分
						print_dict = {
							page_height: 9.3,
							page_width: 21.0,
							orientation: "portrait",
							header_template: "",
							footer_template: ""
						}
						break;
					case '4':  //80mm
						print_dict = {
							page_width: 8,
							orientation: "portrait",
							header_template: "",
							footer_template: ""
						}
						break;
					case '5':  //110mm
						print_dict = {
							page_width: 11,
							orientation: "portrait",
							header_template: "",
							footer_template: ""
						}
						break;
					default:
						print_dict = {}
						break;
				}
                let urlPrex = this.printType===2?'https://anhuiyaoying.com/pdf':'https://anhuiyaoying.com/localPDF'
                let pageType = '', filename = '', pageUrl = '';
				switch (this.params.type) {
					case 'sale':
						pageType = 'pdf_saleOrder'
						filename = this.params.corp_order_no+'.pdf'
						pageUrl = urlPrex+'/saleOrder.html?bussiness='+this.params.unique_order_no+
							'&pk_id='+this.params.pk_id+'&corp_order_no='+this.params.corp_order_no+'&corp='+this.corp+
                            '&project=jcy'
                        if (is_post){
                            pageUrl = urlPrex+'/postOrder.html?bussiness='+this.params.unique_order_no+
                                '&pk_id='+this.params.pk_id+'&corp_order_no='+this.params.corp_order_no+'&corp='+this.corp+
                                '&project=jcy'
                        }
						break;
					case 'purchase':
						pageType = 'pdf_purchaseOrder'
						filename = this.params.corp_order_no+'.pdf'
						pageUrl = urlPrex+'/purchaseOrder.html?bussiness='+this.params.unique_order_no+
							'&pk_id='+this.params.pk_id+'&corp_order_no='+this.params.corp_order_no+'&corp='+this.corp+
                            '&project=jcy'
						break;
					case 'customer':
						pageType = 'pdf_customerBill'
						filename = '客户对账单.pdf'
						pageUrl = 'https://anhuiyaoying.com/pdf/customerBill.html?corp='+this.corp+
							'&customer='+this.params.customer+'&begin='+this.params.begin+'&end='+this.params.end
						break;
					case 'supplier':
						pageType = 'pdf_supplierBill'
						filename = '供货商对账单.pdf'
						pageUrl = 'https://anhuiyaoying.com/pdf/supplierBill.html?corp='+this.corp+
							'&supplier='+this.params.supplier+'&begin='+this.params.begin+'&end='+this.params.end
						break;
					default:
						break;
				}
                let that = this
				if (that.showPreview || that.showPrint) return
				
				if (type && type=='preview'){
					that.showPreview = true
				}else{
					that.showPrint = true
				}

                if (that.printType === 1){
                    this.showPreview = false
                    this.showPrint = false
                    window.open(pageUrl)
                }else{
                    urlToPdf({
                        corpId: this.corp,
                        pdf_file_add: {
                            unique_order_no: this.params.unique_order_no,
                            unique_type: pageType,
                            show_filename: filename,
                            req_url: pageUrl
                        },
                        print_dict: print_dict,
                        domain: 'anhuiyaoying.com',
                        cookies_dict: {
                            Authorization_TOKEN: getToken()
                        }
                    }).then(res => {
                        this.showPreview = false
                        this.showPrint = false
                        if (res.code == 200){
                            let url = res.data.pdf_url
                            if (type && type=='preview'){
                                window.open(res.data.pdf_url)
                            }else{
                                that.startPrintJob(res.data.id)
                            }
                        }else{
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            // 开启打印任务
            startPrintJob(id) {
                let params = {};
				switch (this.params.selectedSize) {
					case '1':  //A4
						params = {
							dmPaperSize: 0,
							dmPaperLength: 2970,
							dmPaperWidth: 2100
						}
						break;
					case '2':  //A4二等分
						params = {
							dmPaperSize: 0,
							dmPaperLength: 1390,
							dmPaperWidth: 2100
						}
						break;
					case '3':  //A4三等分
						params = {
							dmPaperSize: 0,
							dmPaperLength: 930,
							dmPaperWidth: 2100
						}
						break;
					case '4':  //80mm
						params = {
							dmPaperSize: 0,
							dmPaperWidth: 800
						}
						break;
					case '5':  //110mm
						params = {
							dmPaperSize: 0,
							dmPaperWidth: 1100
						}
						break;
					default:
						break;
				}
				addPrintTasks({
					corp: this.corp,
					pdf_file_id: id,
					add_job_params: params
				}).then(res => {
					if (res.code == 200){
						this.$message.success('打印任务发送成功')
                        this.$emit('submit', 'success')
					}
				})
            },
            bandDeviceCommit() {
                var that = this
                that.$refs['addForm'].validate(valid => {
                    if(!valid) return
                    
                    that.bandForm.corp = that.corp
                    bandDevice(that.bandForm).then(res => {
                        if (res.code == 200){
                            that.$message.success('绑定成功')
                            that.getDeviceList()
                        }else{
                            that.showBandDeviceAlert = false
                        }
                    })
                })
            }
        }
    }
</script>

<style lang="less" scoped>
	@import '../style/mixin.less';
    .print_view {
        padding: 0 15px;
        min-height: 400px;
        max-height: 400px;
        overflow-y: auto;
        position: relative;
        .header {
            display: flex;
            align-items: center;
            height: 30px;
            gap: 50px;
            margin-bottom: 20px;
            .txt {
                font-weight: bold;
            }
        }
        .steps {
            height: 240px;
            padding: 0 10px 20px 10px;
        }
        .print_btn {
            position: absolute;
            bottom: 0;
            width: 100%;
            height: 50px;
            text-align: center;
            .btn {
                width: 120px;
                height: 40px;
                font-size: 15px;
                text-align: center;
                line-height: 40px;
                border-radius: 5px;
                margin: 0 auto;
                background: @blue;
                color: #fff;
                cursor: pointer;
            }
        }
        .list {
            .yunhe {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            .print_list {
                margin-top: 10px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .card {
                    width: 90%;
                    border: 1px solid #ddd;
                    background-color: #fff;
                    border-radius: 8px;
                    margin-bottom: 20px;
                    padding-bottom: 10px;
                    .top {
                        background-color: @blue;
                        border-top-right-radius: 8px;
                        border-top-left-radius: 8px;
                        display: flex;
                        align-items: center;
                        height: 40px;
                        color: #fff;
                        font-size: 14px;
                        padding-left: 10px;
                        img {
                            width: 20px;
                            height: 20px;
                        }
                    }
                    .txt {
                        font-size: 13px;
                        padding: 10px 15px 0 15px;
                    }
                    .mohe {
                        display: flex;
                        flex-direction: column;
                    }
                }
                .circle {
                    width: 24px;
                    height: 24px;
                    border: 1px solid @blue;
                    border-radius: 10px;
                }
                .select {
                    border: none;
                }
            }
        }
        .btns {
            position: absolute;
            height: 50px;
            bottom: 0;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-evenly;
            .btn {
                width: 120px;
                height: 40px;
                background: @blue;
                color: #fff;
                font-size: 15px;
                text-align: center;
                line-height: 40px;
                border-radius: 5px;
                cursor: pointer;
            }
        }
    }
</style>